package otherPractice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SocketServer {

	public  void inWords(Socket client) throws IOException{
		int flag = 0;
		Scanner sc = new Scanner(System.in);
		System.out.println();
		System.out.println("please input next words...");
		String words = sc.nextLine();
		
		Writer writer = new OutputStreamWriter(client.getOutputStream());
		
		writer.write(words);
		writer.write("........end\n");
		writer.flush();
		
		if((flag = words.indexOf("oever")) != -1){
			writer.close();
			client.close();
		}
			
		if(!client.isClosed()){
			outWords(client);
		}
		
		
		//writer.close();
		//client.close();
	}
	
	public void outWords(Socket client) throws IOException{
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
		StringBuilder sb = new StringBuilder();
		String temLine ;
		int index = 0;
		while((temLine=reader.readLine()) != null){
			if((index = temLine.indexOf("over")) != -1){
				System.out.println("The other part has ended the conversation");
			}else{
				if((index = temLine.indexOf("end")) != -1){
					sb.append(temLine);
					break;
				}
			}
			
			sb.append(temLine);
			
		}
		
		System.out.println("from client:" + sb);
		
		if(!client.isClosed()){
			inWords(client);
		}
		
		reader.close();
		client.close();
	}
	
	
	
	
	public static void main(String[] args) throws IOException{
		SocketServer demo = new SocketServer();
		
		int port = 8899;
		ServerSocket server = new ServerSocket(port);
		Socket socket = server.accept();
		
		demo.outWords(socket);
		demo.inWords(socket);
		
		
		socket.close();
		
	}
	
	
}
